package per.destiny.seckill.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import per.destiny.seckill.pojo.User;
import per.destiny.seckill.service.GoodsService;
import per.destiny.seckill.vo.GoodsDetailVo;
import per.destiny.seckill.vo.GoodsVo;
import per.destiny.seckill.vo.RespBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller()
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    @RequestMapping(value = "/toList", method = RequestMethod.GET, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从Redis中获取页面，如果不为空，直接返回页面
        String goodsListHtml = (String) valueOperations.get("goodsList");
        if (StringUtils.isNotBlank(goodsListHtml)) {
            return goodsListHtml;
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        // 如果为空，手动渲染，存入Redis并返回
        // goodList表示模板名称，webContext表示web上下文
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        goodsListHtml = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (StringUtils.isNotBlank(goodsListHtml)) {
            // 设置一分钟的缓存，让库存能够更新
            valueOperations.set("goodsList", goodsListHtml, 1, TimeUnit.MINUTES);
        }
        return goodsListHtml;
    }


    /**
     * 页面已经放到static目录下了，后缀为htm
     *
     * @param model
     * @param user
     * @param goodsId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "detail/{goodsId}", method = RequestMethod.GET)
    @ResponseBody
    public RespBean detail(Model model, User user, @PathVariable("goodsId") Long goodsId, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        model.addAttribute("goods", goodsVo);

        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date now = new Date();
        // 秒杀状态
        int seckillStatus = 0;
        // 秒杀倒计时,秒
        long remainSeconds = 0;
        if (now.before(startDate)) {
            // 秒杀还未开始
            remainSeconds = (startDate.getTime() - now.getTime()) / 1000;
        } else if (now.after(endDate)) {
            // 秒杀已经结束
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            // 秒杀中
            seckillStatus = 1;
            remainSeconds = 0;
        }
        /**
         * 前端来做倒计时处理，
         * 此时前端和服务端的时间不是完全一致的，肯定会产生误差，不同的前端误差会有不同。
         * 这种场景不用考虑，因为秒杀本来就是一个看运气的场景。
         * （但是需要保证前端倒计时完毕，服务端即可秒杀，即前端的时间要迟于服务端的时间，因为有网络延迟以及代码执行时间，所以前端直接拿服务端返回的时间处理即可保证前端的时间要迟于服务端的时间），
         */
        model.addAttribute("seckillStatus", seckillStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setUser(user);
        goodsDetailVo.setGoods(goodsVo);
        goodsDetailVo.setSeckillStatus(seckillStatus);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        return RespBean.success(goodsDetailVo);
    }
}
